package xpn.platform.modules.sys.org;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
import org.springframework.data.rest.core.annotation.RestResource;
import org.springframework.data.rest.core.config.Projection;
import xpn.platform.common.repository.XpnRepository;

import java.util.List;

@RepositoryRestResource(path = "orgs", excerptProjection = DefaultProjection.class)
public interface SysOrgDAO extends XpnRepository<SysOrg, Long> {

	/**
	 * 查找所有根组织机构：无父亲机构的所有机构
	 * 
	 * @return
	 */
	@RestResource(exported = false)
	List<SysOrg> findByParentOrgIsNull();

	/**
	 * 查找所有根组织机构：无父亲机构的所有机构: 排除指定ID
	 * 
	 * @return
	 */
	@RestResource(exported = false)
	List<SysOrg> findByParentOrgIsNullAndIdNot(Long exceptId);

	/**
	 * 查找所有机构：父亲机构为指定机构
	 * 
	 * @param parentOrg：指定的父机构
	 * @return
	 */
	@RestResource(exported = false)
	List<SysOrg> findByParentOrg(@Param("parentOrg") SysOrg parentOrg);
	
	/**
	 * 根据老數據id查找機構：郑波2018-3-2增加
	 *
	 */
	@RestResource(path = "byOldId", rel = "byOldId")
	SysOrg findOneByOldId(@Param(value = "param") String oldId);


	@RestResource(path = "byOrgName", rel = "byOrgName")
	SysOrg findOneByOrgName(@Param(value = "param") String orgName);
	
	/**
	 * 根据老數據id查找機構：郑波2018-3-2增加
	 *
	 */
	@Query(value = "select e from SysOrg e where  e.id in (:orgIds) order by e.sortNo asc")
	List<SysOrg> findOneByOrgIdsAndSort(@Param(value = "orgIds") List<Long> orgIds);

	/**
	 * 根据老數據id查找機構：郑波2018-3-2增加
	 *
	 */
	@Query(value = "select e from SysOrg e where  e.id in (:orgIds)")
	List<SysOrg> findOneByOrgIds(@Param(value = "orgIds") List<Long> orgIds);

	List<SysOrg> findByType(Integer type);

}

/**
 * 缺省投影
 *
 * @author bobatkm
 *
 */
@Projection(name = "default", types = { SysOrg.class })
interface DefaultProjection {
	Long getId();

	String getOrgName();

	Integer getType();

	String getOrgCode();

	Float getSortNo();

	@Value("#{true}")
	Boolean getIsLeaf();

	SysOrg getParentOrg();
}

/**
 * 列表投影，用于返回关联属性
 *
 * @author bobatkm
 */
@Projection(name = "list", types = { SysOrg.class })
interface ListProjection {
	Long getId();

	@Value("#{target.getParentOrg()!=null?target.getParentOrg().getId():null}")
	Long getParentId();

	@Value("#{target.fetchAncestorId()}")
	Long getAncestorId();

	@Value("#{target.getChildren().size()==0}")
	Boolean getIsLeaf();

	@Value("#{target.fetchFullName()}")
	String getFullName();

	String getOrgName();

	String getOrgCode();

	Integer getType();

	Float getSortNo();
}